﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Framework.Plugin
{
    public class CMSEventsAggregator
    {
        #region Static Private Ctors

        static CMSEventsAggregator()
        {
            EventsHashtable = new Hashtable();
        }

        #endregion

        protected readonly static Hashtable EventsHashtable= null;

        public void Subscribe<T>(Action<object, CMSEventArgs<T>> eventHanlder)
        {
            if (EventsHashtable.ContainsKey(typeof(T)))
            {
                CMSEventHandler<T> cmsEventHandler = EventsHashtable[typeof(T)] as CMSEventHandler<T>;
                if (cmsEventHandler != null)
                {
                    cmsEventHandler = Delegate.Combine(cmsEventHandler, eventHanlder) as CMSEventHandler<T>;
                }
                else
                {
                    cmsEventHandler = new CMSEventHandler<T>(eventHanlder);
                }
                EventsHashtable[typeof(T)] = cmsEventHandler;
            }
            else
            {
                EventsHashtable.Add(typeof(T), new CMSEventHandler<T>(eventHanlder));
            }
        }

        public void Publish<T>(object sender, CMSEventArgs<T> e)
        {
            if (EventsHashtable.ContainsKey(typeof(T)))
            {
                 CMSEventHandler<T> cmsEventHandler = EventsHashtable[typeof(T)] as CMSEventHandler<T>;
                 if (cmsEventHandler != null)
                 {
                     cmsEventHandler(sender, e);
                 }
            } 
        } 
    }

    public class CMSEventArgs<T> : EventArgs
    {
        public T Value
        {
            get;
            set;
        }
    }

    public delegate void CMSEventHandler<T>(object sender, CMSEventArgs<T> e); 

}
